import axios from 'axios'
import { ElMessage } from 'element-plus'
import config from '@/config'

// 根据配置决定使用代理还是直接请求
const baseURL = config.useProxy 
  ? '/api'  // 开发环境使用 Vite 代理
  : `${config.baseURL}${config.apiPrefix}`  // 生产环境直接请求

const request = axios.create({
  baseURL,
  timeout: config.timeout
})

request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('admin_token')
    if (token) {
      config.headers.token = token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.code === 0) {
      return res
    } else {
      ElMessage.error(res.message || '请求失败')
      return Promise.reject(new Error(res.message || '请求失败'))
    }
  },
  (error) => {
    // 处理401未登录
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      localStorage.removeItem('admin_token')
      localStorage.removeItem('admin_username')
      // 跳转到登录页
      setTimeout(() => {
        window.location.href = '/login'
      }, 1000)
    } else {
      ElMessage.error(error.response?.data?.detail || '请求失败')
    }
    return Promise.reject(error)
  }
)

export default request

